package org.springblogs.batch.processor.stock;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.springblogs.core.Status;
import org.springblogs.dao.StockInfoRepository;
import org.springblogs.dao.StockMarketRepository;
import org.springblogs.model.StockInfo;
import org.springblogs.model.StockMarket;
import org.springblogs.utils.HttpUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class StockInfoItemProcessor extends AbstractBaseItemProcessor<StockMarket, StockInfo> {
	// <div class="sltit"><a name="sz">深圳股票</a></div>
	// <div class="sltit"><a name="sh">上海股票</a></div>
	private static final Pattern PATTERN_MARKET = Pattern
			.compile("<div class=\"sltit\"><a name=\"(s[hz])\"/>([^<>]+)</div>");
	private static final Pattern PATTERN_STOCK = Pattern
			.compile("<li><a target=\"_blank\" href=\"[^<>]+\">([^<>]+)\\(([0-9]{6})\\)</a></li>");

	private static final String ALL_STOCK_URL = "http://quote.eastmoney.com/stocklist.html";
	@Autowired
	private StockInfoRepository stockInfoRepository;

	@Override
	public StockInfo process(StockMarket item) throws Exception {
		log.debug(item);
		try {
			String res = HttpUtils.get(ALL_STOCK_URL, "gb2312");
			Matcher matcher = PATTERN_MARKET.matcher(res);
			Timestamp createdTime = new Timestamp(System.currentTimeMillis());
			int start = 0;
			while (matcher.find()) {
				start = matcher.start();
//				String market = matcher.group(1);
//				String marketName = matcher.group(2);
//				if (stockMarketRepository.getOne(market) == null) {
//					StockMarket m = new StockMarket();
//					m.setMarket(market);
//					m.setName(marketName);
//					m.setUpdatedDate(new Timestamp(System.currentTimeMillis()));
//					stockMarketRepository.save(m);
//				}

			}
			// 上海股票
			log.debug("shang hai stock checking");
			findStock("sh", res.substring(0, start), createdTime);
			log.debug("shang hai stock finished checking");
			// 深圳股票
			log.debug("shen zhen stock checking");
			findStock("sz", res.substring(start), createdTime);
			log.debug("shen zhen stock finished checking");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	private void findStock(String market, String res, Timestamp createdTime) {
		Matcher stockMatch = PATTERN_STOCK.matcher(res);
		List<StockInfo> stocks = new ArrayList<>();
		Calendar c = Calendar.getInstance();
		Date endDate = c.getTime();
		c.set(1990, 1, 1, 0, 0, 0);
		Date startDate = c.getTime();
		while (stockMatch.find()) {
			String code = stockMatch.group(2);
			log.debug(String.format("check %s ...", code));
			if (!stockInfoRepository.existsById(code)) {
				log.debug(String.format("%s not exist, create it", code));
				String name = stockMatch.group(1);
				StockInfo stock = new StockInfo();
				stock.setCode(code);
				stock.setName(name);
				stock.setMarket(market);
				stock.setUpdatedDate(createdTime);
				stock.setOnline(1);
				stock.setStartDate(startDate);
				stock.setEndDate(endDate);
				stock.setStatus(Status.FAIL);
				stocks.add(stock);
				if (stocks.size() > 100) {
					stockInfoRepository.saveAll(stocks);
					stockInfoRepository.flush();
					log.debug(String.format("%s find 100 stocks to saved", market));
					stocks.clear();
				}
			} else {
				log.debug(String.format("%s exist, skip it", code));
			}
		}
		if (stocks.size() > 0) {
			stockInfoRepository.saveAll(stocks);
			log.debug(String.format("%s find %s stocks to saved", market, stocks.size()));
		}
	}
}
